<script setup lang="ts">
import { ref, onMounted, reactive, watch } from "vue";
import { ElMessage, ElForm, ElFormItem, ElInput, ElButton, ElMessageBox, ElSwitch } from "element-plus";
import { useRoute } from "vue-router";
import { getGroupConfigsApi, setGroupConfigsApi } from '@/api/configs/productConfig';

const configGroupName = "performance" // 配置组名
const props = defineProps<{
  productId: number;
}>();
// 定义配置项类型
interface ConfigItem {
  configKey: string;
  configValue: string;
  configDesc: string;
}

const route = useRoute();
const formRef = ref<InstanceType<typeof ElForm>>();

// 定义配置项类型
interface PerformanceConfig {
  hasParamReportLimit: boolean;
  minParamReportInterval: number;
  hasWaveReportLimit: boolean;
  minWaveReportInterval: number;
}

const defaultConfig = {
  hasParamReportLimit: false,
  minParamReportInterval: 1,
  hasWaveReportLimit: false,
  minWaveReportInterval: 1,
}
// 初始化表单数据
const formData = reactive<{
  productId: number;
  groupName: string;
  config: PerformanceConfig;
  updatedAt: string;
}>({
  productId: 0,
  groupName: configGroupName,
  config: Object.assign({}, defaultConfig),
  updatedAt: '',
});

// 表单验证规则
const rules = reactive({
  'config.minParamReportInterval': [
    { required: formData.config.hasParamReportLimit, message: '请输入最小参数数据上报频率', trigger: 'change' },
    { type: 'number', min: 1, message: '必须为正整数', trigger: 'change' }
  ],
  'config.minWaveReportInterval': [
    { required: formData.config.hasWaveReportLimit, message: '请输入最小波形数据上报频率', trigger: 'change' },
    { type: 'number', min: 1, message: '必须为正整数', trigger: 'change' }
  ]
});
watch(() => props.productId, (newVal:number) => {
  if (newVal) {
    formData.config  =  Object.assign({}, defaultConfig)
    formData.productId = newVal;
    loadConfigData();
  }
},{
  deep: true
});
const loadConfigData = () => {
  if(formData.productId){
    // 获取产品配置组数据
    getGroupConfigsApi({
      productId: formData.productId,
      groupName: formData.groupName
    }).then(res => {
      if (res.code === 0 && res.data?.configs) {
        formData.updatedAt = res.data.updatedAt || '';
        try {
          const configData = JSON.parse(res.data.configs[0]?.configValue || '{}');
          Object.assign(formData.config, configData);
        } catch (e) {
          console.error('解析配置数据失败', e);
        }
      }
    });
  }
}

// 切换参数数据上报限制
const toggleParamReportLimit = (value: boolean) => {
  formData.config.hasParamReportLimit = value;
};

// 切换波形上报限制
const toggleWaveReportLimit = (value: boolean) => {
  formData.config.hasWaveReportLimit = value;
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();

    ElMessageBox.confirm(
      '确定要保存当前性能指标配置吗？',
      '确认提交',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      const submitData = {
        productId: formData.productId,
        groupName: formData.groupName,
        configs: [{
          configKey: configGroupName,
          configValue: JSON.stringify(formData.config),
          configDesc: ''
        }]
      };

      await setGroupConfigsApi(submitData);
      ElMessage.success('保存成功');
    }).catch(() => {
      ElMessage.info('已取消保存');
    });
  } catch (error) {
    ElMessage.error('表单验证失败，请检查填写内容');
  }
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
};
</script>

<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="220px" class="form-container">
    <el-form-item label="配置组名" prop="groupName">
      <el-input v-model="formData.groupName" disabled />
    </el-form-item>

    <!-- 参数数据上报频率限制 -->
    <el-form-item label="是否有参数数据上报频率限制" prop="config.hasParamReportLimit">
      <el-switch
        v-model="formData.config.hasParamReportLimit"
        :active-value="true"
        :inactive-value="false"
        @change="toggleParamReportLimit"
      />
    </el-form-item>

    <!-- 最小参数数据上报频率（动态显示） -->
    <el-form-item
      v-if="formData.config.hasParamReportLimit"
      label="最小参数数据上报频率（秒）"
      prop="config.minParamReportInterval"
    >
      <el-input
        v-model.number="formData.config.minParamReportInterval"
        type="number"
        min="1"
        placeholder="请输入最小参数数据上报频率"
      />
      <div class="form-hint"></div>
    </el-form-item>

    <!-- 波形上报频率限制 -->
    <el-form-item label="是否有波形上报频率限制" prop="config.hasWaveReportLimit">
      <el-switch
        v-model="formData.config.hasWaveReportLimit"
        :active-value="true"
        :inactive-value="false"
        @change="toggleWaveReportLimit"
      />
    </el-form-item>

    <!-- 最小波形数据上报频率（动态显示） -->
    <el-form-item
      v-if="formData.config.hasWaveReportLimit"
      label="最小波形数据上报频率（秒）"
      prop="config.minWaveReportInterval"
    >
      <el-input
        v-model.number="formData.config.minWaveReportInterval"
        type="number"
        min="1"
        placeholder="请输入最小波形数据上报频率"
      />
      <div class="form-hint"></div>
    </el-form-item>

    <!-- 更新时间显示 -->
    <el-form-item label="更新时间" >
      <el-input v-model="formData.updatedAt" disabled placeholder="暂无更新时间" />
    </el-form-item>

    <el-form-item class="form-actions">
      <el-button type="primary" @click="submitForm">提交</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>
<style scoped lang="scss">
.form-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}
.form-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 30px;
}
.form-hint {
  color: #606266;
  font-size: 12px;
  margin-top: 5px;
}
::v-deep .el-form-item__content {
  flex: 1;
}
</style>
